#include "worker.h"

int NewUser(userInfo_t *userInfo, threadPool_t *pthreadPool)
{
    char sql[256] = {0};
    time_t timer;
    struct tm *Now;
    time(&timer);
    Now = localtime(&timer);//bug：root目录的父节点也应是自身
    sprintf(sql, "INSERT INTO ServerDir VALUE('root','%s',1,0,0,NULL,'%d-%02d-%02d %02d:%02d:%02d','Root of %s',NULL)",
            userInfo->username,
            Now->tm_year + 1900,
            Now->tm_mon + 1,
            Now->tm_mday,
            Now->tm_hour,
            Now->tm_min,
            Now->tm_sec,
            userInfo->username);
    //puts(sql);
    m_MysqlQuery(pthreadPool->mysql, sql);
    bzero(sql, sizeof(sql));
    sprintf(sql, "select id from ServerDir Where comment='Root of %s' && owner='%s'", userInfo->username, userInfo->username);
    //puts(sql);
    m_MysqlQuery(pthreadPool->mysql, sql);

    MYSQL_ROW row;
    MYSQL_RES * results = mysql_store_result(pthreadPool->mysql);
    row = mysql_fetch_row(results);
    //printf("row:%s\n",row[0]);
    strncpy(userInfo->rootId, row[0], sizeof(row[0]));

    char salt[32]={0};
    GenRandStr(salt,8);
    printf("salt1:%s\n",salt);
    packPassword(salt,userInfo->password);
    printf("password:%s\n",userInfo->password);
    takeSalt(salt,userInfo->password);
    printf("salt2:%s\n",salt);
    sprintf(sql, "INSERT INTO userInformation VALUE('%s','%s','%s')", userInfo->username,userInfo->rootId, userInfo->password);
    //puts(sql);
    m_MysqlQuery(pthreadPool->mysql, sql);
    //puts("Q3");
    mysql_free_result(results);
    userInfo->pos=atoi(userInfo->rootId);
}

int signUp(int netfd,userInfo_t *userInfo, threadPool_t *pthreadPool)
{
    int si = si_connect;
    sendInfo(netfd, &si, sizeof(si));
    int ret = recvInfo(netfd, userInfo);
    puts(userInfo->username);
    puts(userInfo->password);
    if (ret>0)
    {
        NewUser(userInfo, pthreadPool);
        sendInfo(netfd, userInfo, sizeof(userInfo_t));
    }
}
